package com.pan.api.convert.impl;


import com.pan.api.anno.PanComment;
import com.pan.api.convert.ControllerStrategy;
import com.pan.api.convert.MethodStrategy;
import com.pan.api.entity.ControllerInformation;
import com.pan.api.entity.MethodInformation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * 包级私有的类不能被外面反射
 */

public class ControllerStrategyImpl extends ControllerStrategy {

    public ControllerStrategyImpl(MethodStrategy methodStrategy) {
        super(methodStrategy);
    }

    @Override
    public ControllerInformation handle(Class clazz) {

        ControllerInformation ci = new ControllerInformation();
        if (clazz.isAnnotationPresent(RestController.class)){
            ci.setJsonXml(true);
        }else if (clazz.isAnnotationPresent(Controller.class)){
            ci.setJsonXml(false);
        } else {
            throw new RuntimeException("This class isn't Controller: "+clazz);
        }


        if (clazz.isAnnotationPresent(RequestMapping.class)){
            RequestMapping requestMapping = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
            String[] value = requestMapping.value();
            String pre = value.length == 0?"":Arrays.stream(value).map(s -> "/".concat(s)).reduce("[",(p,c)->p+c+", ").concat("]");
            ci.setPrefix(pre);
        }
        if (clazz.isAnnotationPresent(PanComment.class)){
            PanComment panComment = (PanComment) clazz.getAnnotation(PanComment.class);
            ci.setComment(panComment.value());
        }
//        else {
//            ci.setComment("not exists comment");
//        }

        ci.setControllerName(clazz.getName());
        List<MethodInformation> apiList = super.methodStrategy.handle(clazz);
        ci.setMethodList(apiList);
        return ci;
    }
}
